<?php
namespace libs;

use Exception;
use components\O;

class URIProcess{
	const FORM_URL_ENCODE = "application/x-www-form-urlencoded";
	const JSON       	  = "application/json";
	const MULTI_FORM      = "multipart/form-data";

	public static function getDomain(){
		return $_SERVER['SERVER_NAME'];
	}
	public static function getRequestAPI(){
		return $_SERVER['REQUEST_URI'];
	}
	public static function getRequestMethod(){
		return $_SERVER['REQUEST_METHOD'];
	}
	public static function parseScenarioUrl(){
		$rawUrl = self::getRequestAPI();
		//var_dump($rawUrl);
		//preg_match('#\/(.*)\/(.*)\?#iUs',$rawUrl,$uri);
		if(strpos($rawUrl,'?') !== false){
			preg_match('#^\/(.*)\?#iUs',$rawUrl,$uri);
		}else{
			preg_match('#^\/(.*)$#iUs',$rawUrl,$uri);
		}
		if(empty($uri)){
			throw new Exception("url request invalid");
		}
		$url = explode('/', $uri[1]);
		$controller = $action = '';
		if(count($url) == 2){//一层
			$controller = 'controllers' . '\\' . Util::strToCamel($url[0]) . 'Controller' ;
			$action = 'action' . Util::strToCamel($url[1]);
		}
		if(count($url) == 3){//模块
			$modules = O::$app->modules;
			if(empty($modules) || !in_array($url[0],array_keys($modules))){
				throw new Exception("modules request not exist");
			}
			$namespace = (new $modules[$url[0]]['class'])->controllerNamespace;
			$controller = $namespace . '\\' . Util::strToCamel($url[1]) . 'Controller' ;
			$action = 'action' . Util::strToCamel($url[2]);
		}
		if(empty($controller) || empty($action)){
			$backTrace = debug_backtrace();
			throw new Exception("attention:url request controller or action not auth.[controller]:$controller,[action]:$action" . json_encode($backTrace));
		}
		return [$controller,$action];
	}
	public static function parseRequestParams(){
		return array_merge(self::parseQueryParams(),self::parseBodyParams());
	}
	public static function parseQueryParams(){
		$uri = self::getRequestAPI();
		if(($len = strpos($uri, '?')) !== false){
			$str = substr($uri, $len + 1);
			$params = explode('&', $str);
			$params = array_map(function($arr){
				$raw = explode('=', $arr);
				return [$raw[0] , $raw[1]];
			},$params);
			$get = [];
			foreach($params as $one){
				$get[$one[0]] = $one[1];
			}
			return $get;
		}
		return [];
	}
	public static function getRequestContentType(){
		if(self::getRequestMethod() == 'GET'){
			return 'GET';
		}elseif (self::getRequestMethod() == 'POST') {
			if($_SERVER['CONTENT_TYPE'] == self::JSON){
				return 'JSON';
			}

			if($_SERVER['CONTENT_TYPE'] == self::FORM_URL_ENCODE || 
				strpos($_SERVER['CONTENT_TYPE'],self::MULTI_FORM) !== false){
				return 'FORM';
			}
		}
	}
	public static function parseBodyParams(){
		if(self::getRequestContentType() == 'JSON'){
			return json_decode(file_get_contents("php://input"),true);
		}
		if(self::getRequestContentType() == 'FORM'){
			return $_POST;
		}
		return [];
	}

	public static function dispatch(Array $data)
	{
		header('Content-type: text/json');
		echo json_encode($data);
		flush();
		exit();
	}
}